package com.aop.example.aspect;

import com.aop.example.annotation.Authority;
import com.aop.example.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

import static cn.hutool.core.lang.Console.log;

@Slf4j
@Aspect
@Component
public class AuthAspect {

    @Autowired
    AuthorityUtil authorityUtil;

//    @Pointcut("@annotation(com.aop.example.annotation.Authority)")
//    public void AuthPointCut(){}

    //校验权限
//    @Around("AuthPointCut()")
    @Around("@annotation(com.aop.example.annotation.Authority)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        //
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Authority authority = method.getAnnotation(Authority.class);
        if(authority != null){
            Map<String, Object> map = ThreadLocalUtil.get();
            if(map == null || map.isEmpty()){
                log("【日志记录】:线程中保存数据为空");
                throw new RuntimeException("线程中保存数据为空");
            }

            System.out.println(map);
            Integer userId = (Integer) map.get("userId");
            if (!authorityUtil.checkAuth(userId, authority.value())) {
                log("【日志记录】:该用户没有该权限");
                throw new RuntimeException("用户没有该权限");
            }

        }
        return point.proceed();
    }
}
